﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Text;
using WebUI.DAL;

namespace WebUI.BL.Contact
{
    public class ContactBL
    {
        public IEnumerable<tbl_Contact> GetContacs()
        {
            var dbcontext = new AdlerContextDataContext();
            return dbcontext.tbl_Contacts.OrderBy(x=>x.Status).ThenBy(x=>x.Id);
        }

        public IEnumerable<tbl_Contact> GetContacsByMutltiFilter(string subject,DateTime? frmDate, DateTime? toDate)
        {
            var dbcontext = new AdlerContextDataContext();
            var query = dbcontext.tbl_Contacts.AsQueryable();
            if (!String.IsNullOrEmpty(subject))
                query = query.Where(c => c.Subject.Contains(subject));
            if (frmDate != null)
                query = query.Where(c => c.CreatedOn >= frmDate);
            if (toDate != null)
                query = query.Where(c => c.CreatedOn < toDate);
            return query.AsEnumerable().Select(x => x).OrderBy(x => x.Status).ThenBy(x => x.Id); 
        }

        public void Insert(tbl_Contact contact)
        {
            var adlerContextDb = new AdlerContextDataContext();
            try
            {
                adlerContextDb.tbl_Contacts.InsertOnSubmit(contact);
                adlerContextDb.SubmitChanges();
            }
            catch (ChangeConflictException)
            {
                //neu xay ra loi rollback lai
                adlerContextDb.ChangeConflicts.ResolveAll(RefreshMode.KeepCurrentValues);
                adlerContextDb.SubmitChanges();
            }
        }

        public tbl_Contact GetContactById(int id)
        {
            var dbcontext = new AdlerContextDataContext();
            return dbcontext.tbl_Contacts.FirstOrDefault(x => x.Id == id);
        }
    }
}
